package cn.fbs.service;

import cn.fbs.dao.dm.DMNewTargetMapper;
import cn.fbs.model.NewTCodeTargetType;
import cn.fbs.model.NewTcodeTargetTree;
import cn.fbs.util.StringUtil;
import cn.fbs.vo.NewTargetVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class NewTargetService {

    @Autowired
    private DMNewTargetMapper targetMapper;

    public List<NewTcodeTargetTree> getFirstLevel() {

        List<NewTcodeTargetTree> list = targetMapper.getFirstLevel();
        return list;
    }

    public List<NewTcodeTargetTree> findAllByTree() {
        //1.找到一级目标
        List<NewTcodeTargetTree> firstLevel = getFirstLevel();

        //select * from ZCQB.T_CODE_TARGET_TYPE where XH like concat(XH,"%") and length(XH) = xxx order by XH

        List<NewTcodeTargetTree> collect = firstLevel.stream().map(item -> {
            item.setChildrenTarget(getChildrens(item));
            return item;
        }).collect(Collectors.toList());
        return collect;
    }


    //获取当前目标下的所有子目标
    public List<NewTcodeTargetTree> getChildrens(NewTcodeTargetTree root) {
        String xh = root.getXh();
        int length = xh.length() + 2;
        List<NewTcodeTargetTree> list = targetMapper.getChildrens(length, xh);
        List<NewTcodeTargetTree> collect = list.stream().map(item -> {
            item.setChildrenTarget(getChildrens(item));
            return item;
        }).collect(Collectors.toList());
        return list;
    }


    //获取当前目标下的子目标
    public List<NewTcodeTargetTree> getChildrens(String zbnm) {
        if (zbnm == null) {
            List<NewTcodeTargetTree> firstLevel = getFirstLevel();
            return firstLevel;
        } else {
            String xh = targetMapper.getTargetByNm(zbnm);
            int length = xh.length() + 2;
            List<NewTcodeTargetTree> list = targetMapper.getChildrens(length, xh);
            return list;
        }

    }


    public String insert(NewTargetVo targetVo) {

        //查詢名称是否重复
        if (targetMapper.selectCountByname(targetVo.getMc(), "") > 0) {
            return "401,已存在相同名称的目标!";
        }
        String xh = targetMapper.getXh(targetVo.getZbnm());
        //生成装备内码
        String subZbnm = System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 5);
        NewTCodeTargetType targetType = new NewTCodeTargetType();
        targetType.setZbnm(subZbnm);
        targetType.setSjsj(new Date());
        targetType.setMc(targetVo.getMc());
        //同级目录
        if (targetVo.getType() == 0) {
            //找到当前目录最大的那个XH,在最大序号的基础上加1，判断是否达到99，因为限制时两位树，所以不能超过99
            String maxXh =  targetMapper.getMaxTarget(xh);
            if (maxXh.endsWith("99")){
                return "500,同级目录下目标超过最大限制";
            }
            BigDecimal myXh = new BigDecimal(maxXh).add(new BigDecimal(1));
            String zeroStr = getZeroStr(xh.length());
            DecimalFormat decimalFormat = new DecimalFormat(zeroStr);
            String formatXh = decimalFormat.format(myXh);
            targetType.setXh(formatXh);
        } else {
            //增加下级目录
            if (xh.length()>=4+9*2){
                return "500,目标树最多可以拥有十级";
            }
            String maxSubXh = targetMapper.getSubMaxTarget(xh);
            if (StringUtil.isEmpty(maxSubXh)) {
                String xhs = xh + "01";
                targetType.setXh(xhs);
            } else {
                if (maxSubXh.endsWith("99")){
                    return "500,同级目录下目标超过最大限制";
                }
                BigDecimal myXh = new BigDecimal(maxSubXh).add(new BigDecimal(1));
                String zeroStr = getZeroStr(maxSubXh.length());
                DecimalFormat decimalFormat = new DecimalFormat(zeroStr);
                String formatXh = decimalFormat.format(myXh);
                targetType.setXh(formatXh);
            }
        }
        targetMapper.insert(targetType);
        return "200,新增成功";
    }

    private String getZeroStr(int length) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            buffer.append("0");
        }
        return buffer.toString();
    }

    public int update(NewTCodeTargetType targetType) {
        //校验名称是否重复
        if (targetMapper.selectCountByname(targetType.getMc(), targetType.getZbnm()) > 0) {
            return -1;
        }
        targetMapper.update(targetType);
        return 0;
    }


    /**
     * 若删除父级目标，则子级目标也应当删除
     * @param ZBNM
     * @return
     */
    public Map<String, Object> delete(String ZBNM) {

        Map<String, Object> map = new HashMap<>();
        String xh = targetMapper.getXh(ZBNM);
        targetMapper.delete(xh);
        map.put("message", "删除成功");
        return map;
    }

    public List<NewTCodeTargetType> getTargetByMC(String mc) {
        List<NewTCodeTargetType> list = targetMapper.getTargetByMC(mc);
        System.out.println("getTargetByMC_end");
        return list;
    }


    /**
     * @Description: 查询全部信息分类
     * @Param: [query]
     * @return: com.github.pagehelper.PageInfo<com.bonc.entity.TCodeTargetType>
     * @Author: zlj
     * @Date: 2020/12/22
     **/

    public List<NewTcodeTargetTree> getTargetTree() {
        List<NewTcodeTargetTree> targetTrees = targetMapper.selectAll();
        ArrayList<NewTcodeTargetTree> topNodes = formatTree(targetTrees);
        return topNodes;

    }

    public ArrayList<NewTcodeTargetTree> formatTree(List<NewTcodeTargetTree> targetTrees) {
        ArrayList<NewTcodeTargetTree> topNodes = new ArrayList<>();
        HashMap<String, ArrayList<NewTcodeTargetTree>> map = new HashMap<>();
        for (NewTcodeTargetTree targetTree : targetTrees) {
            String xh = targetTree.getXh();
            if (xh.length() == 4) {
                topNodes.add(targetTree);
                continue;
            }
            String topXh = xh.substring(0, xh.length() - 2);
            if (!map.containsKey(topXh)) {
                map.put(topXh, new ArrayList<NewTcodeTargetTree>());
            }
            ArrayList<NewTcodeTargetTree> list = map.get(topXh);
            list.add(targetTree);
            Collections.sort(list);
        }
        Collections.sort(topNodes);
        addSub(topNodes, map);
        return topNodes;
    }

    /**
     * 判断当前目标是否有子目标，如果有则继续迭代,如果没有则跳到下一个
     *
     * @param topNodes
     * @param map
     */
    private void addSub(ArrayList<NewTcodeTargetTree> topNodes, HashMap<String, ArrayList<NewTcodeTargetTree>> map) {
        for (NewTcodeTargetTree topNode : topNodes) {
            String topXh = topNode.getXh();
            if (map.containsKey(topXh)) {
                topNode.setChildrenTarget(map.get(topXh));
                addSub(map.get(topXh), map);
            } else {
                continue;
            }
        }

    }


    public Map<String, Object> getMessageByNm(String zbnm) {
        Map<String, Object> map = new HashMap<>();
        String xh = targetMapper.getXh(zbnm);
        int length = xh.length() + 2;
        int count = targetMapper.selectCountByXH(length, xh);
        System.out.println("getMessageByNm_1");
        if (count > 0) {
            System.out.println("getMessageByNm_2");
            map.put("message", "此目标下含有子集数据");
        }
        System.out.println("getMessageByNm_3end");
        return map;
    }


}
